package utils;/*
 * H2parent
 * utils
 * @author wuqiang@kedacom.com
 * @date 2019/1/29
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class H2JdbcUtil {

    private static final Logger logger= Logger.getLogger("utils.H2JdbcUtil");

     private static final String URL="jdbc:h2:file:F:/test"; //嵌入式模式，第一次连接会在F盘生成一个文件。
    //private static final String URL="jdbc:h2:mem:testWuq;DB_CLOSE_DELAY=-1"; //使用内存模式
    //private static final String URL="jdbc:h2:tcp://localhost//F://test"; //使用服务模式，如果服务器不开，会获取不到
    private static final String USERNAME="sa"; //H2数据库默认的用户名和密码
    private static final String PASSWORD="";

    static {
        try {
            Class.forName("org.h2.Driver");
        } catch (ClassNotFoundException e) {
            logger.log(Level.CONFIG,"加载JDBC驱动报错");
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接出错！");
        }
        return connection;
    }

    /**
     * 关闭资源
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection){
        close(connection,null,null);
    }
    public static void close(Connection connection,Statement statement){
        close(connection,statement,null);
    }
}
